#include "event_driven/event_driver.h"

#include <iostream>
#include <thread>

void Scheduler::start()
{
    running.store(true, std::memory_order_seq_cst);

    eventThread = std::thread(&Scheduler::eventLoop, this);
}

void Scheduler::stop()
{
    if (!running.load())
        return;
    running.store(false, std::memory_order_seq_cst);
    eventThread.join();
}

void Scheduler::eventLoop()
{
    while (running.load(std::memory_order_seq_cst))
    {
        EventHandler handler;
        {
            std::lock_guard<std::mutex> lcok(mtx);
            if (events.empty())
                continue;

            const Event& event = events.top();
            handler = event.handler;
            events.pop();
        }

        handler();

        std::this_thread::sleep_for(std::chrono::microseconds(10));
    }
}

void Scheduler::postEvent(Event&& event)
{
    std::lock_guard<std::mutex> lock(mtx);
    events.push(std::move(event));
}